package com.iweb.day11;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * @author WuYongheng
 * @date 2021/11/28
 * @description 模拟转帐业务无事务控制
 */
public class Test8 {
    public static void main(String[] args) throws SQLException {
        Connection conn = null;
        PreparedStatement p1 = null;
        PreparedStatement p2 = null;
        // 数据库连接信息
        String url = "jdbc:oracle:thin:@127.0.0.1:1521:xe";
        String username = "hr";
        String password = "123456";
        try {
            // 加载驱动
            Class.forName("oracle.jdbc.driver.OracleDriver");
            // 连接对象
            conn = DriverManager.getConnection(url, username, password);
            if (conn != null) {
                System.out.println("连接成功");
            }
            // 1. 关闭自动提交:
            conn.setAutoCommit(false);
            // 操作
            // p1扣钱   p2加钱
            //   扣钱
            String minusSql = "update bank set money=money-? where bname=?";
            p1 = conn.prepareStatement(minusSql);
            p1.setInt(1, 100);
            p1.setString(2, "张三");
            // 加钱业务
            String addSql = "update bank set money=money+? where bname=?";
            p2 = conn.prepareStatement(addSql);
            p2.setInt(1, 100);
            p2.setString(2, "李四");

//            执行
            p1.execute();
            int a = 10 / 0;
            p2.execute();
            // 若没有出现异常，提交
            conn.commit();
            System.out.println("转账结束");
        } catch (Exception e) {
            // 若发生异常，回滚事务
            if (conn != null) {
                try {
                    conn.rollback();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }

        } finally {
            // 释放资源
            try {
                if (p1 != null) {
                    p1.close();
                }
                if (p2 != null) {
                    p2.close();
                }
                if (conn != null) {
                    conn.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
